//确认订单
let api = require("../../server/Api.js")
let app = getApp();
const util = require("../../utils/util.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    curTab: 0,
    intoType: 0, //0购物车进入 1：立即购买进入
    emptyType: 0,
    showPayTypeDialog: false,
    showCouponsDialog: false,
    items: [],
    totalPrice: 0,
    selectAddress: null, //选择的地址
    orderId: "", //订单id;
    shopId: 0,
    shopInfo: {},
    mobile: "",
    name: "",
    nameTemp: "",
    mobileTemp: "",
    hiddenmodalput: true,
    hiddennamemodalput: true,
    hiddenmodalpay: true,
    distance: "?km",
    canDelivery: false,
    isPayed: false,
    contactList: [],
    contactNameList: [],
    contactMobileList: [],
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    let userInfo = app.globalData.userBean;
    if (!(userInfo && userInfo.consumerId)) {
      return;
    }
    let jsonItems = options.items;
    var items = [];
    if (jsonItems) {
      jsonItems = jsonItems.replace(/-\|-/g, "?").replace(/-\|\|-/g, "=");
      items = JSON.parse(jsonItems);

      let intoType = 0;
      if (options.type) {
        intoType = options.type;
      }

      this.setData({
        shopId: items[0].storeId,
        items: items,
        intoType: intoType
      })
      this.setTotalPrice()
    } else if (options.shopId) {
      this.setData({
        shopId: options.shopId,
        intoType: 0
      })
      this.queryCart();
    }
    this.getShopInfo();

    this.getContactList();
  },

  getContactList() {
    let that = this;
    let userInfo = app.globalData.userBean;
    console.log(userInfo)
    if (userInfo && userInfo.consumerId && userInfo.phone) {
      this.setData({
        name: userInfo.nickName,
        mobile: userInfo.phone
      })
    }
    api.getHistoryConsigneeAndTelephone(userInfo.consumerId).then(res => {
      that.setData({
        contactList: res
      })
      if (that.data.contactList.length > 0) {
        for (let i = 0; i < that.data.contactList.length; i++) {
          if (i === 0) {
            that.setData({
              name: that.data.contactList[0].consignee,
              mobile: that.data.contactList[0].telephone
            })
          }
          if (!that.data.contactNameList.includes(that.data.contactList[i].consignee)) {
            that.data.contactNameList.push(that.data.contactList[i].consignee)
          }
          if (!that.data.contactMobileList.includes(that.data.contactList[i].telephone)) {
            that.data.contactMobileList.push(that.data.contactList[i].telephone)
          }
        }
      }
    })
  },

  getShopInfo: function() {
    let that = this;
    api.getShopInfo(this.data.shopId || app.globalData.shopId).then(res => {
      console.log("店铺信息:", res);
      //请求成功
      that.setData({
        shopInfo: res
      })
      app.globalData.qqmapsdk.calculateDistance({
        mode: "straight",
        to: res.latitude + "," + res.longitude,
        success: function(res) {
          if (res.result.elements.length > 0) {
            that.setData({
              distance: app.setMtoKm(res.result.elements[0].distance)
            })
          }
        },
        fail: function(error) {
          console.error("获取距离失败", error);
        },
      });
    }).catch(msg => {
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  queryCart: function() {
    let that = this;
    let userInfo = app.globalData.userBean;
    if (userInfo && userInfo.consumerId) {
      let prams = {
        pageSize: 100,
        pageNumber: 1,
        storeId: that.data.shopId,
        platformId: app.globalData.platformId,
        userId: userInfo.consumerId
      };
      api.queryCartList(prams).then(res => {
        console.log("购物车:", res.records[0].cartVO);
        for (let i = 0; i < res.records.length; i++) {
          for (let j = 0; j < res.records[i].cartVO.length; j++) {
            res.records[i].cartVO[j].skuImage = app.resetImageUrl(res.records[i].cartVO[j].skuImage, 172, 172);
          }
        }
        if (res.records.length > 0) {
          that.setData({
            items: res.records[0].cartVO
          })
        } else {
          that.setData({
            items: []
          })
        }
        that.setTotalPrice()

      }).catch(msg => {
        console.log(msg);
        app.showToast("获取购物车数量失败!");
      })
    } else {
      that.setData({
        list: list
      })
    }
  },

  setTotalPrice: function() {
    let that = this;
    var totalPrice = 0;
    //计算合计价格
    for (var i = 0; i < that.data.items.length; i++) {
      totalPrice += (parseFloat(that.data.items[i].goodsPrice) * 100 * parseInt(that.data.items[i].goodsQuantity)) / 100;
    }
    that.setData({
      totalPrice: totalPrice.toFixed(2)
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
    if (that.data.selectAddress) {
      that.setData({
        canDelivery: false
      })
      app.globalData.qqmapsdk.calculateDistance({
        mode: "straight",
        from: that.data.selectAddress.latitude + "," + that.data.selectAddress.longitude,
        to: that.data.shopInfo.latitude + "," + that.data.shopInfo.longitude,
        success: function(res) {
          if (res.result.elements.length > 0) {
            if (res.result.elements[0].distance <= 2000) {
              that.setData({
                canDelivery: true
              })
            } else {
              tt.showModal({
                title: '该地址超出配送范围',
                content: '请更换收货地址，或选择到店提货。',
                showCancel: false,
                confirmText: "知道了"
              })
            }
          }
        },
        fail: function(error) {
          console.error("获取距离失败", error);
        },
      });
    }
  },

  //提交订单
  submit: function(e) {
    let that = this;
    //商品项
    let items = this.data.items;
    var carts = [];
    console.log(this.data.intoType)
    that.setData({
      loading: true
    })
    setTimeout(function() {
      that.setData({
        loading: false
      })
    }, 600)
    if (this.data.intoType == 1) {
      let userBean = app.globalData.userBean;
      app.showLoading()
      api.addCart(items[0].goodsQuantity, items[0].skuId, userBean.consumerId).then(res => {
        console.log(res)
        carts.push(res.recId)
        tt.hideLoading()
        that.submitOrder(e, carts)
      }).catch(msg => {
        tt.hideLoading()
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message)
      })
    } else {
      for (var i = 0; i < items.length; i++) {
        carts.push(items[i].recId);
      }
      that.submitOrder(e, carts)
    }

  },
  submitOrder(e, carts) {
    let that = this;
    let shippingId = 3;
    //收地址项
    let address = this.data.selectAddress;
    if (shippingId === 2 && !address) {
      app.showToast("请选择收货地址");
      return;
    }
    if (shippingId === 3 && this.data.name == "") {
      app.showToast("请输入提货人");
      that.setData({
        nameFocus: true
      })
      return;
    }
    if (shippingId === 3 && this.data.mobile == "") {
      app.showToast("请输入预留号码");
      that.setData({
        mobileFocus: true
      })
      return;
    }
    if (this.data.mobile.length != 11) {
      app.showToast("预留电话必须是11位数")
      that.setData({
        mobileFocus: true
      })
      return;
    }

    let curDate = new Date();
    let mouth = curDate.getMonth() + 1;
    mouth = (mouth > 9 ? (mouth + "") : ("0" + mouth));
    let day = curDate.getDay();
    day = (day > 9 ? (day + "") : ("0" + day));
    curDate = curDate.getFullYear() + "-" + mouth + "-" + day + " " + this.data.time + ":00";
    //备注(非必填)
    let remark = e.detail.value.remark;

    //立即购买的数量
    let nowBuyCount = this.data.items[0].goodsQuantity;

    let userBean = app.globalData.userBean;
    let params = {
      userId: userBean.consumerId,
      shippingId: shippingId,
      cartIds: carts,
      source: 6,
      consignee: that.data.name,
      mobile: that.data.mobile,
      telphone: that.data.mobile,
      address: that.data.shopInfo.address,
      postscript: remark, //备注
      submitType: that.data.intoType,
      buyNum: nowBuyCount
    }
    console.log(params);
    app.showLoading()
    api.submitOrder(params).then(res => {
      tt.hideLoading()
      that.setData({
        orderId: res.orderId
      })
      this.showPayTypeDialog();
    }).catch(msg => {
      tt.hideLoading()
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message)
    })
  },
  showPayTypeDialog: function() {
    this.setData({
      showPayTypeDialog: true,
    })
  },
  //选择地址
  toSelect: function() {
    tt.navigateTo({
      url: '../setting-my-address/setting-my-address?type=1',
    })
  },
  // 显示优惠券弹窗
  showCouponsDialog: function(e) {
    this.setData({
      showCouponsDialog: true,
    })
  },
  //显示支付方式弹窗
  showPayTypeDialog: function() {
    this.setData({
      showPayTypeDialog: true,
    })
  },
  //关闭订单支付
  closeOrderPay: function(isPayed) {
    let that = this;
    if (!isPayed) {
      tt.showModal({
        title: '提示',
        content: '是否要退出订单支付？',
        success: function(e) {
          if (e.confirm) {
            that.setData({
              showPayTypeDialog: false,
            })
            if (that.data.orderId && that.data.orderId != "") {
              tt.redirectTo({
                url: '../order-detail/order-detail?orderId=' + that.data.orderId,
              })
            } else {
              tt.navigateBack({
                delta: 1,
              })
            }
          }
        },
      })
    } else {
      that.setData({
        showPayTypeDialog: false,
        hiddenmodalpay: false
      })
    }
  },
  //隐藏所有弹窗
  hiddenDialog: function(e) {
    console.log(e)
    e.detail = e.detail || {}
    this.closeOrderPay(e.detail.payed);
  },
  //选择器
  tabSelect: function(e) {
    console.log("");
    let index = e.currentTarget.id;
    this.setData({
      curTab: index
    })

  },
  viewmap(e) {
    console.log(e);
    tt.openLocation({
      latitude: parseFloat(e.currentTarget.dataset.lat),
      longitude: parseFloat(e.currentTarget.dataset.lng),
      scale: 18
    })
  },
  goShowNameInput() {
    let that = this;
    if (that.data.contactNameList.length > 1) {
      tt.showActionSheet({
        itemList: that.data.contactNameList,
        success(res) {
          that.setData({
            name: that.data.contactNameList[res.tapIndex]
          })
        },
        fail(res) {
          that.setData({
            nameFocus: true
          })
        }
      })
    }
  },
  goShowInput() {
    let that = this;
    if (that.data.contactMobileList.length > 1) {
      tt.showActionSheet({
        itemList: that.data.contactMobileList,
        success(res) {
          that.setData({
            mobile: that.data.contactMobileList[res.tapIndex]
          })
        },
        fail(res) {
          that.setData({
            mobileFocus: true
          })
        }
      })
    }
  },
  mobileInput(e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  nameInput(e) {
    this.setData({
      name: e.detail.value
    })
  },
  toIndex() {
    tt.switchTab({
      url: '../index/index'
    })
  },
  toOrderDetail() {
    tt.redirectTo({
      url: '../order-detail/order-detail?orderId=' + this.data.orderId,
    })
  }
})